package com.study.talk.common.config;




import com.study.talk.common.filter.ExceptionHandlerFilter;
import com.study.talk.common.filter.RequestCountFilter;
import com.study.talk.common.security.SimpleAccessDeniedHandler;
import com.study.talk.common.security.SimpleAuthenticationEntryPoint;
import com.study.talk.common.security.SimpleTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Resource
    private SimpleAuthenticationEntryPoint simpleAuthenticationEntryPoint;
    @Resource
    private SimpleAccessDeniedHandler simpleAccessDeniedHandler;

    @Resource
    private SimpleTokenFilter simpleTokenFilter;

    @Resource
    private RequestCountFilter requestCountFilter;

    @Resource
    private ExceptionHandlerFilter exceptionHandlerFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().cors().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests()
                .antMatchers("/file/pic/**","/register/simple","/image","/image/**","/test","/login","/**")
                .permitAll()
                .anyRequest()
                .authenticated();
        http.logout().disable();
        http.exceptionHandling()
                .authenticationEntryPoint(simpleAuthenticationEntryPoint)
                .accessDeniedHandler(simpleAccessDeniedHandler);
        http.addFilterBefore(exceptionHandlerFilter, CorsFilter.class);
        http.addFilterBefore(requestCountFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(simpleTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
